import { ClassicModel } from '../../models/classic.js'
import { LikeModel } from '../../models/like.js'

let classicModel = new ClassicModel()
let likeModel = new LikeModel()

/**
 * 此处要改为Component，而非原来的Page
 * 当然需要去掉Page中自带的生命周期函数
 * 并添加methods，将自定义函数移动到methods中
 */
Component({
  properties: {
    cid: Number,
    type: Number
  },

  /**
   * 页面的初始数据
   */
  data: {
    classic: null,
    isFirst: false,
    isLatest: true,
    likeCount: 0,
    likeStatus: false,
    isShowNav: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  attached: function(options) {
    const { cid, type } = this.properties
    if (!cid) {
      this.setData({
        isShowNav: true
      })
      classicModel.getLatest((res) => {
        const { fav_nums: likeCount, like_status: likeStatus } = res
        
        this.setData({
          classic: res,
          likeCount,
          likeStatus
        })
      })
    } else {
      this.setData({
        isShowNav: false
      })
      classicModel.getById(cid, type, res => {
        const { id, type, index } = res
        this._getLikeStatus(id, type)
        this.setData({
          classic: res,
          isLatest: classicModel.getIsLatest(index),
          isFirst: classicModel.getIsFirst(index)
        })
      })
    }
  },

  methods: {
    /**
     * n-like自定义点赞事件
     */
    handleLike (e) {
      const { behavior } = e.detail
      const { id, type } = this.data.classic

      likeModel.like(behavior, id, type)
    },

    /**
     * n-nav自定义上一页事件
     */
    hanldePrev (e) {
      this._getClassic('next')
    },

    /**
     * n-nav自定义下一页事件
     */
    handleNext (e) {
      this._getClassic('previous')
    },

    /**
     * 获取classic数据
     * direction: previous表示上一期，next表示下一期
     * 越往下期刊值index越小
     */
    _getClassic (direction) {
      const { index } = this.data.classic

      classicModel.getClassic(index, direction, (res) => {
        const { index: curIndex, id, type } = res

        this._getLikeStatus(id, type)
        this.setData({
          classic: res,
          isLatest: classicModel.getIsLatest(curIndex),
          isFirst: classicModel.getIsFirst(curIndex)
        })
      })
    },

    _getLikeStatus (artId, category) {
      likeModel.getClassicLikeStatus(artId, category, (res) => {
        const { fav_nums: likeCount, like_status: likeStatus } = res
        this.setData({
          likeCount,
          likeStatus
        })
      })
    }
  }
})